//
//  RecordHomeController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/8.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
import Moya
import ObjectMapper
import AVFoundation
class RecordHomeController: WarningBaseController {
    
    
    fileprivate var clockState:Int? = 5
    fileprivate var getInfoState:Bool? = false
    fileprivate var ctTionState:CertificationStatus?
    var timeAlert1:TWLAlertView?
    fileprivate var workDayType : Int?
    fileprivate var _tableView: UITableView!
    fileprivate var workerTimeState:String?
    fileprivate var player:AVAudioPlayer?
    var vasionModel: NewVesionModel?
    var companyInfoModel:CompanyInfoModel?
    fileprivate var currentHomeInfoModel:SignHomeInfoModel?
    var isIngore:Bool?
    fileprivate var ctCustomView:CTHomeAlertView?
    fileprivate lazy var recordComAlertView:HomeRecordAlertView = {
        let alertView = HomeRecordAlertView()
        return alertView
    }()
    
    
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            _tableView.rowHeight = UITableViewAutomaticDimension
            _tableView.estimatedRowHeight = 270
            _tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
            //            _tableView.register(ProjectCell.self, forCellReuseIdentifier: "\(ProjectCell.self)")
            _tableView.register(UINib.init(nibName: "ProjectNormalCell", bundle: nil), forCellReuseIdentifier: "ProjectNormalCell")
            _tableView.register(ProjectNoDataCell.self, forCellReuseIdentifier: "\(ProjectNoDataCell.self)")
            regClass(_tableView, cell: RecordHome_SignInSignOutCell.self)
            _tableView.register(RecordTimelineCell.self, forCellReuseIdentifier: "\(RecordTimelineCell.self)")
            
            _tableView.register(UINib.init(nibName: "LaborInfoCell", bundle: nil), forCellReuseIdentifier: "LaborInfo")
            _tableView.register(UINib.init(nibName: "HomeProjectCell", bundle: nil), forCellReuseIdentifier: "HomeProject")
            _tableView.register(UINib.init(nibName: "ClockStateCell", bundle: nil), forCellReuseIdentifier: "ClockState1")
            _tableView.register(UINib.init(nibName: "ClockStateNCell", bundle: nil), forCellReuseIdentifier: "ClockState2")
            _tableView.register(UINib.init(nibName: "ClockStateFCell", bundle: nil), forCellReuseIdentifier: "ClockState3")
            
            return _tableView
        }
    }
    
    var customView = BadgeView(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
    
    
    /***本地变量***/
    let locationService = BMKLocationService()
    
    let service = TrackUploadService.sharedInstance
    
    var projectModel: ProjectModel?//当前项目
    var recordPolicy: RecordPolicy? //当前项目对应的签到策略
    var inRange: Bool = false//判断是否在签到范围内。默认不在
    
    var recordItems: [RecordModel]? //签到记录（用于 项目记录时间 条目）
    var currentVasion:String?
    //界面显示的时间，默认是当前时间
    fileprivate var displayDate:String?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if (self.tableView.mj_header.scrollViewOriginalInset.top > 0 && self.tableView.mj_header.state == MJRefreshState.idle) {
            let oldContentInset = self.tableView.contentInset;
            self.tableView.contentInset = UIEdgeInsets.init(top: 0, left: oldContentInset.left, bottom: oldContentInset.bottom, right: oldContentInset.right);
            }
        self.locationService.delegate = self
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        /*流程：
         1.每次进入RecordViewController就检查登录状态
         2.
         没有登录 -> 跳到LoginViewController。
         登录了 -> 获取认证状态信息
         3.成功获取认证状态后，保存这个状态
         4.检查当前的认证状态，根据状态不同走向不同结果
         */
        
        self.checkCertificationStatus()
        
        customView.image = UIImage(named: "reply_n")
        customView.isUserInteractionEnabled = true
    customView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doLeftAction)))
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: customView)
        
        //左上角未读标记处理
        (UIApplication.shared.delegate as! AppDelegate).remoteNotificationHandler = {[unowned self](result) in
            if result {
                self.customView.showBadge = true
            }
            else {
                self.customView.showBadge = false
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.locationService.delegate = nil
        WWProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addNotificationObserve()
        
        self.workerTimeState = "z"
        self.title = "考勤"
        self.isIngore = false
        self.setupCurrentVasionData()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "统计", style: .done, target: self, action: #selector(doRightAction))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
       
        
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(kNotificationAlertSignedInSignedOut), object: nil)
        
        // Do any additional setup after loading the view.
        self.baseView.addSubview(self.tableView)
        
       // self.tableView.contentInset = UIEdgeInsets(top: -33, left: 0, bottom: 0, right: 0)
        
        
        self.tableView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self.baseView)
        }
        
        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            
            self.getAllData()
            self.checkCertificationStatus()
            
        }
        
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        self.getAllData()
        LoginAuthenticationService.verifyLoginStatus { (response) in
            if response.success {
                if !self.tableView.mj_header.isRefreshing {
                 self.tableView.mj_header.beginRefreshing()
                }
                self.checkVersionData()
            }
            else {
                let vc = LoginViewController()
            UIApplication.shared.delegate?.window!?.rootViewController = vc
            }
        }
        
        //判断定位位置和指定位置是否在策略要求范围内
        self.service.twoPointWithinTheSpecifiedRange = {[unowned self](result) in
            self.inRange = result
           // self.tableView.reloadRows(at: [IndexPath.init(row: 0, section: 3)], with: .none)
            self.tableView.reloadData()
        }
        
    }
    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(MWNotificationMainRefresh)
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    @objc func getMWLocationData(notification:Notification) {
         self.tableView.mj_header.beginRefreshing()
    }
    fileprivate func setupCurrentVasionData(){
        let infoDictionary = Bundle.main.infoDictionary
        if let infoDictionary = infoDictionary {
            self.currentVasion = (infoDictionary["CFBundleShortVersionString"] as! String)
        }
    }
    fileprivate func checkVersionData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        print(accountId)
        
        LCAPiSubManager.request(.GetVersonData(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let vasionNum : Int = jsonString["VersionNum"] as? Int else{
                    return
                }
                
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                     self.vasionModel = Mapper<NewVesionModel>().map(JSONObject: resultDic)
                }
                if self.currentVasion != self.vasionModel?.VersionCode && vasionNum > 0{
                    if self.vasionModel?.IsForce == true{
                        let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                        let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                            let url = NSURL(string: (self.vasionModel?.AppPath)!)
                            UIApplication.shared.openURL(url! as URL)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        })
                        alert.addAction(gotoAppstore)
                        self.present(alert, animated: true, completion: {
                            
                        })
                    }else{
                        let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                        
                        let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                            let url = NSURL(string: (self.vasionModel?.AppPath)!)
                            UIApplication.shared.openURL(url! as URL)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        })
                        let refuseApp = UIAlertAction(title: "残忍拒绝", style: .cancel, handler: { (action) in
                            
                        })
                        
                        refuseApp.setValue(UIColor.gray, forKey: "titleTextColor")
                        alert.addAction(gotoAppstore)
                        alert.addAction(refuseApp)
                        self.present(alert, animated: true, completion: {
                            
                        })
                    }
                }
            }
        }
    }
    @objc func doRightAction() {
        let statisticsVc = StatisticsHomeController()
        statisticsVc.hidesBottomBarWhenPushed = true
    self.navigationController?.pushViewController(statisticsVc, animated: true)
    }
    @objc func doLeftAction() {
        let vc = MessageListController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc private func doNotificationAction() {
        self.tableView.mj_header.beginRefreshing()
    }
    func getAllData() {
        self.displayDate = dateToString(date: Date())
      LoginAuthenticationService.setupcurrentDate(range: self.displayDate!)
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        self.getProjectData {
            dispatchGroup.leave()
        }
       // dispatchGroup.wait()
        dispatchGroup.enter()
        self.setupCompanyInfoData {
            dispatchGroup.leave()
        }
        dispatchGroup.notify(queue: DispatchQueue.main) {
            self.getRecordData()
            self.getRecordPolicy()
        }
    }
    
    fileprivate func getSignHomeInfo(_ completion:@escaping () -> Void){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
       
    LCAPiSubManager.request(.GetSignHomeInfo(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    completion()
                    self.getInfoState = false
                    return
                }
                self.getInfoState = true
                completion()
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    self.currentHomeInfoModel = Mapper<SignHomeInfoModel>().map(JSONObject: resultDic)
                    self.tableView.reloadData()
                }
            }
        }
    }
    fileprivate func getSystemTime(_ completion:@escaping () -> Void){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
       
      LCAPiSubManager.request(.GetSignStageDate(AccountId: accountId, demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? String else{
                    return
                }
                let index1 = resultDic.index(of: "T")
                self.displayDate = String(resultDic.prefix(upTo: index1!))
               
            LoginAuthenticationService.setupcurrentDate(range: self.displayDate!)
                self.tableView.reloadData()
                completion()
            }
        }
    }
    fileprivate func setupCompanyWorkTypeData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let companyID = self.companyInfoModel?.CompanyID else {
            return
        }
     LCAPiSubManager.request(.GetWorkDayType(AccountId: accountId, contructionCompanyID:companyID )) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? Int else{
                    return
                }
                
                self.workDayType = resultDic
                self.tableView.reloadData()
            }
        }
    }
    fileprivate func getWorkerTimeStateData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard  let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
    LCAPiSubManager.request(.GetWorkTimeState(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    self.workerTimeState = "z"
                    self.tableView.reloadData()
                    return
                }
                if let resultDic = jsonString["Result"] as? String {
                    self.workerTimeState = resultDic
                    
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    
    fileprivate func setupCompanyInfoData(_ completion:@escaping () -> Void){
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        print(accountId)
        guard let companyID = WWUser.sharedInstance.companyID else{
            
            return
        }
    LCAPiSubManager.request(.GetMigrantWorkerCompanyInfo(AccountId: accountId, CompanyID: companyID)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    self.tableView.reloadData()
                    return
                }
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    self.companyInfoModel = Mapper<CompanyInfoModel>().map(JSONObject: resultDic)
                    self.setupCompanyWorkTypeData()
                    self.tableView.reloadData()
                }
                completion()
            }
        }
    }
    
    //获取项目数据。（section1的数据）
    private func getProjectData(_ completion:@escaping () -> Void) {
        //获取当前选中的项目，默认项目列表的第一个就是选中的项目
        ProjectModel.projectList(pageIndex: 1, pageSize: 1) { (response) in
            if response.success {
                
                if let values = response.value,values.count > 0 {
                    let model = values[0]
                    
                    if model.isAppSelected && model.isWorking && model.isBlackList == false{//签到界面的项目如果完结了，那么默认选择是没有的。
                    self.projectModel = values[0]
                    self.getWorkerTimeStateData()
                    self.getSignHomeInfo {
                        
                    }
                    self.getSystemTime {
                        completion()
                    }
                        
                    }else {
                        self.projectModel = nil
                        completion()
                    }
                }
                else {
                    self.projectModel = nil
                    completion()
                }

                self.tableView.reloadData()
                
            }
            else {
                
            }
            self.tableView.mj_header.endRefreshing()
        }
    }
    fileprivate func setupCertificationAlertView(){
        guard (self.projectModel?.isCertification)! else {
            self.pushToRecordView()
            return
        }
        if self.projectModel?.isCertification == true{
            self.timeAlert1 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            let custom : CTApplicationView = CTApplicationView.init(frame: CGRect(x: 0, y: 0, width: 250, height: 130))
            custom.applicationButton.addTarget(self, action: #selector(applicationAllInfoClick), for: .touchUpInside)
            custom.contentLabel.text = "该项目是实名制的项目，请先通过实名认证，再来签到"
            custom.applicationButton.setTitle("实名认证", for: UIControlState.normal)
            custom.cancelButton.addTarget(self, action: #selector(firstAlertCancelClick), for: .touchUpInside)
            self.timeAlert1?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 250, height: 130))
            let keyWindow = UIApplication.shared.keyWindow
            keyWindow?.addSubview(self.timeAlert1!)
        }else{
            guard LoginAuthenticationService.getupIngore() != "1" else{
                self.pushToRecordView()
                return
            }
            if self.projectModel?.isSignSalary == true{
                self.timeAlert1 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
                let custom : CTHomeAlertView = CTHomeAlertView.init(frame: CGRect(x: 0, y: 0, width: 250, height: 175))
                self.ctCustomView = custom
                custom.makeSureButton.addTarget(self, action: #selector(cTMakeSureButton), for: .touchUpInside)
                custom.cancelButton.addTarget(self, action: #selector(timeAlertCancelClick), for: .touchUpInside)
                custom.otherButton.addTarget(self, action: #selector(otherButtonClick), for: .touchUpInside)
                self.timeAlert1?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 250, height: 175))
                let keyWindow = UIApplication.shared.keyWindow
                keyWindow?.addSubview(self.timeAlert1!)
            }
        }
    }
    
    fileprivate func pushToRecordView(){
        
        let vc = SignedOperatedViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.projectModel = self.projectModel
        vc.signedType = SignedType.signedIn
        vc.recordOperationHandler = {
            self.tableView.mj_header.beginRefreshing()
        }
        vc.audioPlayer = {(value,isRecord) in
            let ringStr = LoginAuthenticationService.getupRingtone()
            if ringStr == "1" && isRecord == true{
            self.playAudioAction("sign_sucess", type: ".m4a")
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc fileprivate func otherButtonClick(){
        if self.isIngore == false{
            self.isIngore = true
        self.ctCustomView?.otherButton.setImage(UIImage.init(named: "rent_selected"), for: .normal)
        }else{
            self.isIngore = false
   self.ctCustomView?.otherButton.setImage(UIImage.init(named: "rent_noSelect"), for: UIControlState.normal)
        
        }
        
    }
    @objc fileprivate func cTMakeSureButton(){
        self.timeAlert1?.cancleView()
        if self.isIngore == false{
            self.setupPushToCertificationPage()
        }else{
        LoginAuthenticationService.setupIngore(username: "1")
            self.setupPushToCertificationPage()
        }
    }
    fileprivate func setupPushToCertificationPage(){
    let certification = CertificationFirstPageViewController(nibName: "CertificationFirstPageViewController", bundle: nil)
    
      certification.hidesBottomBarWhenPushed = true
 self.navigationController?.pushViewController(certification, animated: true)
    }
    
    @objc fileprivate func applicationAllInfoClick(){
        self.timeAlert1?.cancleView()
        if self.ctTionState == .beReturn {
            let beReturn = HaveBeenReturnViewController(nibName: "HaveBeenReturnViewController", bundle: nil)
            beReturn.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(beReturn, animated: true)
        }else if self.ctTionState == .certificationInProgress {
            let authenData = AuthenDataViewController(nibName: "AuthenDataViewController", bundle: nil)
            authenData.cTStatus = self.ctTionState
            authenData.navigationItem.hidesBackButton = false
            authenData.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(authenData, animated: true)
        }else{
        self.setupPushToCertificationPage()
        }
    }
    @objc fileprivate func firstAlertCancelClick(){
        self.timeAlert1?.cancleView()
    }
    @objc fileprivate func timeAlertCancelClick(){
        self.timeAlert1?.cancleView()
        if self.isIngore == false{
            self.pushToRecordView()
        }else{
        LoginAuthenticationService.setupIngore(username: "1")
        self.pushToRecordView()
        }
    }   
    
    //获取签到记录。
    func getRecordData() {
        if let model = self.projectModel {
            
            RecordModel.getRecordData(demandBaseMigrantWorkerID: model.demandBaseMigrantWorkerID!, signedDate: self.displayDate!){(response) in
                if response.success {
                    self.recordItems = response.value
                    self.setupSignStateNotifition()
                    //获取到签到记录，更新2，3。  section2根据签到记录最后一条确定显示哪个按钮。
                    
                    self.tableView.reloadSections(IndexSet.init(integer: 4), with: .automatic)
                    self.tableView.reloadSections(IndexSet.init(integer: 3), with: .none)
                }
                else {
                  //  WWError(response.message)
                }
            }
        }
    }
    fileprivate func setupSignStateNotifition(){
        let center = NotificationCenter.default
        let notificationName = NSNotification.Name.init(MWSignStateNotification)

        center.post(name: notificationName, object: nil, userInfo: ["sign":self.recordItems?.last?.signedType ?? "1","project":self.projectModel ?? "1"])
    }
    //获取签到策略
    func getRecordPolicy() {
        if let model = self.projectModel {
            RecordPolicy.getRecordPolicy(aID: model.marketSupplyBaseID!, completionHandler: { (response) in
                if response.success {
                    self.recordPolicy = response.value
                    
                    if self.recordPolicy != nil {
                        if model.demandBaseMigrantWorkerID != nil{
                            //获取签到策略后开始上传轨迹
                            self.service.add(self.recordPolicy!, demandBaseMigrantWorkerId: model.demandBaseMigrantWorkerID!)
                            
                            self.service.start()
                        }
                    }
                }
                else {
                   
                }
            })
        }
        
    }
    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
            WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
                
            }
        })
    }
    
}

//MARK:tableView
extension RecordHomeController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 4 {//签到记录
            return self.recordItems?.count ?? 0
        }
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
//        if (self.companyInfoModel != nil) {
//            return 5
//        }
        return 5
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (self.companyInfoModel != nil) {
            
            return CGFloat([105,80, 50, 200, 45][indexPath.section])
        }
        return CGFloat([0,80, 50, 200, 45][indexPath.section])
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {//项目
             let projectModel = self.projectModel
                let cell = tableView.dequeueReusableCell(withIdentifier: "HomeProject", for: indexPath) as! HomeProjectCell
                if (self.projectModel != nil) {
                    cell.adressImage.isHidden = false
                    cell.projectName.isHidden = false
                    cell.adressLabel.isHidden = false
                    cell.noDataImage.isHidden = true
                    cell.noDataLabel.isHidden = true
                    cell.projectName.text = projectModel?.projectName
                    cell.adressLabel.text = projectModel?.address
                }else{
                cell.adressImage.isHidden = true
                cell.projectName.isHidden = true
                cell.adressLabel.isHidden = true
                cell.noDataImage.isHidden = false
                cell.noDataLabel.isHidden = false
                }
                return cell
        }else if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "LaborInfo", for: indexPath) as! LaborInfoCell
            if (self.companyInfoModel != nil) {
                cell.contentView.isHidden = false
                if (self.projectModel != nil) {
                    cell.companyName.text = self.projectModel?.companyName
                    
                    if self.projectModel?.workDayType == 2{
                        if ((self.projectModel?.workHours) != nil){
                           cell.agreedWages.text = (self.projectModel?.hourSalary)! + "元/小时"
                        }else{
                            cell.agreedWages.text = "暂无"
                        }
                    }else{
                        if ((self.projectModel?.daySalary) != nil){
                            cell.agreedWages.text = (self.projectModel?.daySalaryNew)! + "元/工"
                        }else{
                          cell.agreedWages.text = "暂无"
                        }
                    }
                    cell.settlementCycle.text = self.projectModel?.SalaryAutoPeriod
                    cell.workSort.text = self.projectModel?.WorkType
                    
                    if (self.projectModel?.WorkTimeQuantum?.contains("第二天"))!{
                        let myQuantum = self.projectModel?.WorkTimeQuantum?.replacingOccurrences(of: "", with: "第二天")
                      cell.workTime.text = myQuantum
                    }else{
                    cell.workTime.text = self.projectModel?.WorkTimeQuantum
                    }
                }else{
                    cell.companyName.text = self.companyInfoModel?.CompanyName
                    if self.workDayType == 2{
                        if (self.companyInfoModel!.DaySalary != nil) {
                            cell.agreedWages.text = String(self.companyInfoModel!.HourSalary!) + "元/小时"
                        }else{
                            cell.agreedWages.text = "暂无"
                        }
                    }else{
                        if (self.companyInfoModel!.DaySalary != nil) {
                            cell.agreedWages.text = String(self.companyInfoModel!.DaySalary!) + "元/天"
                        }else{
                            cell.agreedWages.text = "暂无"
                        }
                    }
                    
                    cell.settlementCycle.text = self.companyInfoModel?.SalaryAutoPeriod
                    cell.workSort.text = self.companyInfoModel?.MigrantWorkType
                    if (self.companyInfoModel?.WorkTimeQuantum?.contains("第二天"))!{
                        let myQuantum = self.companyInfoModel?.WorkTimeQuantum?.replacingOccurrences(of: "", with: "第二天")
                        cell.workTime.text = myQuantum
                    }else{
                        cell.workTime.text = self.companyInfoModel?.WorkTimeQuantum
                    }
                }
            }else{
               cell.contentView.isHidden = true
            }
            
            return cell
        }else if indexPath.section == 2 {//日期
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath)
            cell.selectionStyle = .none
            cell.textLabel?.text = self.displayDate
            cell.textLabel?.textAlignment = .center
           // cell.textLabel?.textColor = colorWith255RGB(233, g: 233, b: 233)
            return cell
        }
        else if indexPath.section == 3 {//签到主界面
            
            if self.getInfoState == true{
                if self.currentHomeInfoModel?.WorkState == 0{
                    let cell : ClockStateNCell = tableView.dequeueReusableCell(withIdentifier: "ClockState2") as! ClockStateNCell
                    cell.mwWorkState = self.workerTimeState!
                    cell.setupCellDataWithModel(self.currentHomeInfoModel!, state: true, recordArray: self.recordItems)
                    let tap = UITapGestureRecognizer(target: self, action: #selector(goToRecordPage(_:)))
                    cell.topView.addGestureRecognizer(tap)
                    
                    
                    return  cell
                }
                if self.currentHomeInfoModel?.WorkState == 1{
                    let cell : ClockStateFCell = tableView.dequeueReusableCell(withIdentifier: "ClockState3") as! ClockStateFCell
                    let tap = UITapGestureRecognizer(target: self, action: #selector(goToRecordPage(_:)))
                    cell.topView.addGestureRecognizer(tap)
                    cell.mwWorkState = self.workerTimeState!
                cell.setupCellDataWithModel(self.currentHomeInfoModel!, recordArray: self.recordItems)
                    return  cell
                }
                
                if self.currentHomeInfoModel?.WorkState == 2{
                    let cell : ClockStateNCell = tableView.dequeueReusableCell(withIdentifier: "ClockState2") as! ClockStateNCell
                    let tap = UITapGestureRecognizer(target: self, action: #selector(goToRecordPage(_:)))
                    cell.topView.addGestureRecognizer(tap)
                    cell.mwWorkState = self.workerTimeState!
                cell.setupCellDataWithModel(self.currentHomeInfoModel!, state: false, recordArray: self.recordItems)
                    return  cell
                }
            }
            
            let cell = getCell(tableView, cell: RecordHome_SignInSignOutCell.self, indexPath: indexPath)
            guard let model = projectModel else {
                cell.noData = true
                return cell
            }
            cell.mwWorkState = self.workerTimeState!
            cell.noData = false
            cell.bind(self.recordItems)
            cell.inRange = self.inRange
            
            //点击签入按妞
            cell.entryButtonTouchHandler = {[unowned self] in
            self.checkCertificationStatus()
         WWUser.sharedInstance.ensureCertificationStatus { (status) in
            self.ctTionState = status
                if status != CertificationStatus.authenticated{
                    self.setupCertificationAlertView()
                    
                }else{
                    self.pushToRecordView()
                }
            }
                
            }
            
            //点击签出按妞
            cell.exitButtonTouchHandler = {
                let vc = SignedOperatedViewController()
                vc.hidesBottomBarWhenPushed = true
                vc.projectModel = model
                vc.signedType = SignedType.signedOut
                vc.audioPlayer = {(value,isRecord) in
                    let ringStr = LoginAuthenticationService.getupRingtone()
                    if ringStr == "1" && isRecord == true{
                    self.playAudioAction("signWork_sucess", type: ".m4a")
                    }
                }
                vc.recordOperationHandler = {
                  tableView.mj_header.beginRefreshing()
                }
                
            self.navigationController?.pushViewController(vc, animated: true)
                
            }
            cell.checkLocationLabelTouchHandler = {
                let vc = SignedOperatedViewController()
                vc.hidesBottomBarWhenPushed = true
                vc.projectModel = model
                vc.signedType = SignedType.notInRange
            self.navigationController?.pushViewController(vc, animated: true)
            }
            return cell
        }
        else {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(RecordTimelineCell.self)", for: indexPath) as! RecordTimelineCell
            cell.bind(self.recordItems![indexPath.row])
            if indexPath.row == 0 {
                cell.hideTopLine = true
            }
            if let items = self.recordItems {
                if indexPath.row == items.count - 1 {
                    cell.hideBottomLine = true
                }
            }
            return cell
        }
        
    }
    
    
    @objc fileprivate func goToRecordPage(_ tap:UITapGestureRecognizer){
        let model = self.recordItems?.last
        if model?.signedType == .signedOut{
            self.checkCertificationStatus()
            WWUser.sharedInstance.ensureCertificationStatus { (status) in
                self.ctTionState = status
                if status != CertificationStatus.authenticated{
                    self.setupCertificationAlertView()
                    
                }else{
                    
                    self.pushToRecordView()
                    
                }
            }
        }
        if model?.signedType == .signedIn{
            let vc = SignedOperatedViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.projectModel = projectModel
            vc.signedType = SignedType.signedOut
            vc.audioPlayer = {(value,isRecord) in
                let ringStr = LoginAuthenticationService.getupRingtone()
                if ringStr == "1" && isRecord == true{
                    self.playAudioAction("signWork_sucess", type: ".m4a")
                }
            }
            vc.recordOperationHandler = {
                self.tableView.mj_header.beginRefreshing()
            }
            
            self.navigationController?.pushViewController(vc, animated: true)
        }
        if model?.signedType == .notInRange{
            let vc = SignedOperatedViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.projectModel = projectModel
            vc.signedType = SignedType.notInRange
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    fileprivate func playAudioAction(_ name:String,type:String){
        
        let path = Bundle.main.path(forResource: name, ofType: type)
        let soundUrl = NSURL.fileURL(withPath: path!)
        do{
            try self.player = AVAudioPlayer.init(contentsOf: soundUrl)
            self.player?.delegate = self
            self.player?.play()
        }catch let err{
            print("播放失败:\(err.localizedDescription)")
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath == IndexPath(row: 0, section: 1) {
            let vc = ProjectListViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.isChangeSelection = true
            vc.confirmSelection = {(response) in
                self.tableView.mj_header.beginRefreshing()
            }
            if self.recordItems == nil || self.recordItems?.count == 0 {
                vc.projectPreapred = .noAction
            }
            else if self.recordItems!.last?.signedType == .signedIn  {
                vc.projectPreapred = .signedIn
            }
            else if self.recordItems!.last?.signedType == .signedOut
            {
                vc.projectPreapred = .signedOut
            }
            
        self.navigationController?.pushViewController(vc, animated: true)
        }
        
        if indexPath.section == 2 {
            
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 2 && self.projectModel?.isSignSalary==true && self.workerTimeState == "0"{
            self.recordComAlertView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 42)
            return self.recordComAlertView
        }
        let view = UIView()
        if section == 4 {
            let label = UILabel()
            label.frame = CGRect(x: 16, y: 10, width: 150, height: 18)
            label.text = "签到记录时间"
            label.textColor = colorWith255RGB(153, g: 153, b: 153)
            label.font = wwFont_Medium(14)
            view.addSubview(label)
//            label.snp.makeConstraints { (make) in
//                make.right.bottom.equalTo(view)
//                make.left.equalTo(view).offset(20)
//                make.top.equalTo(view).offset(15)
//            }
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.projectModel?.isSignSalary==true&&self.workerTimeState == "0"{

            return [0,2,42,10,30][section]
        }else{
            return [0,2,10,10,30][section]
        }
    }
}

//MARK: 百度地图
extension RecordHomeController: BMKLocationServiceDelegate,AVAudioPlayerDelegate {
    func didUpdate(_ userLocation: BMKUserLocation!) {
        guard let model = self.recordPolicy else{
            return
        }
        if let recordLat = model.latitude, let recordLon = model.longitude, let signedRange = model.signedRange {
            if let recordLatDouble = Double(recordLat), let recordLonDouble = Double(recordLon) {
                let recordCoor = CLLocationCoordinate2D(latitude: recordLatDouble, longitude:recordLonDouble )//目标坐标
                let currentLocation = userLocation.location.coordinate//当前坐标
                let distance = Tool.calculateDistance(a: recordCoor, b: currentLocation)
                
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 3)) as! RecordHome_SignInSignOutCell
                if Double(signedRange)! - distance > 0 {
                    
                    cell.inRange = true
                    
                }
                else {
                    
                    cell.inRange = false
                }
            }
            
        }
    }
}
